package com.sherlocky.document.web;

import com.sherlocky.document.entity.Document;
import com.sherlocky.document.service.DocumentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * ModelAndView 相关控制器
 * @author: zhangcx
 * @date: 2019/8/29 09:46
 */
@Slf4j
@Controller
/** 不生成swagger文档 */
@ApiIgnore
public class DocumentModelViewController {
    @Autowired
    private DocumentService documentService;

    /**
     * 文档预览demo页面
     * @return
     */
    @RequestMapping("/demo")
    public String demo() {
        return "/demo";
    }

    //TODO 写一个大的before？ 指定预览还是编辑？重复调用before编辑要更新redis缓存
    // viewer? editor?

    /**
     * 返回预览页面
     * @param documentKey
     * @param model
     * @return
     */
    @RequestMapping("/viewer/{documentKey}")
    public String view(@PathVariable String documentKey, Model model) {
        model.addAttribute("document", documentService.getDocument(documentKey));
        return "/viewer";
    }

    /**
     * 返回编辑器页面
     * @param documentKey
     * @param userId
     * @param userName
     * @param model
     * @return
     */
    @RequestMapping("/editor/{documentKey}")
    public String edit(@PathVariable String documentKey, @RequestParam String userId, @RequestParam String userName, Model model) {
        Document document = documentService.getDocument(documentKey);
        model.addAttribute("document", document);
        // 如果该格式不支持编辑，则返回预览页面
        if (!documentService.canEdit(document)) {
            return "/viewer";
        }
        model.addAttribute("documentEditParam", documentService.buildDocumentEditParam(userId, userName));
        return "/editor";
    }

    // TODO 删除？
    @RequestMapping("/editor")
    public String editDocFile(@RequestParam String path, @RequestParam(required = false) String name, @RequestParam String userId, @RequestParam String userName, Model model) {
        Document document = documentService.getDocument(documentService.buildDocument(path, name));
        model.addAttribute("document", document);
        // 如果该格式不支持编辑，则返回预览页面
        if (!documentService.canEdit(document)) {
            return "/viewer";
        }
        model.addAttribute("documentEditParam", documentService.buildDocumentEditParam(userId, userName));
        return "/editor";
    }
}
